package com.hexseek.libretvcloud.service;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hexseek.libretvcloud.exception.CustomException;
import com.hexseek.libretvcloud.mapper.ProxyMapper;
import com.hexseek.libretvcloud.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zhougb9
 * @version 1.0.0
 * @description 搜索服务实现类
 * @date 2025/5/14 19:18
 */
@Slf4j
@Service
public class SearchDetailService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private ProxyMapper proxyMapper;

    @Value("${proxy.detail.path}")
    private String detailPath;

    @Value("${proxy.detail.headers.user-agent}")
    private String userAgent;


    public List<VideoInfo> detail(String userId, Integer vodId, Integer proxyId) {

        List<Proxy> proxyList = proxyMapper.selectByProxyId(proxyId);
        if (ObjectUtil.isEmpty(proxyList) && ObjectUtil.isNotEmpty(proxyList.get(0).getApiUrl())) {
            throw new RuntimeException("未找到代理信息，proxyId: " + proxyId);
        }
        // 构建请求URL
        Proxy proxy = proxyList.get(0);
        SearchResponse response = fetchPage(proxy, vodId);

        return convertToSearchResults(userId, response.getList());

    }


    /**
     * 从API获取特定页数据
     */
    private SearchResponse fetchPage(Proxy source, Integer vodId) {
        String url = source.getApiUrl() + detailPath
                .replace("{vodId}", String.valueOf(vodId));

        HttpHeaders headers = new HttpHeaders();
        headers.set("User-Agent", userAgent);
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);

        HttpEntity<?> entity = new HttpEntity<>(headers);

        try {
            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    entity,
                    String.class
            );

            // 检查HTTP状态码
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                String responseBody = responseEntity.getBody();
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.readValue(responseBody, SearchResponse.class);
            } else {
                throw new CustomException("请求失败：" + responseEntity.getStatusCode());
            }
        } catch (RestClientException e) {
            log.error("请求API失败: {}, 错误: {}", url, e.getMessage());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return new SearchResponse();
    }

    /**
     * 转换API返回数据为SearchResult实体
     */
    private List<VideoInfo> convertToSearchResults(String userId, List<Map<String, Object>> items) {
        if (items == null) {
            return Collections.emptyList();
        }

        return items.stream()
                .map(item -> {
                    VideoInfo videoInfo = new VideoInfo();
                    videoInfo.setVodId(Integer.valueOf(String.valueOf(item.getOrDefault("vod_id", ""))));
                    videoInfo.setVodName(String.valueOf(item.getOrDefault("vod_name", "")));
                    videoInfo.setVodActor(String.valueOf(item.getOrDefault("vod_actor", "")));
                    videoInfo.setVodDirector(String.valueOf(item.getOrDefault("vod_director", "")));
                    videoInfo.setVodContent(String.valueOf(item.getOrDefault("vod_content", "")));
                    String vodPlayUrl = String.valueOf(item.getOrDefault("vod_play_url", ""));
                    videoInfo.setVodPlayUrl(parseM3u8Urls(vodPlayUrl));
                    return videoInfo;
                })
                .collect(Collectors.toList());
    }


    private List<String> parseM3u8Urls(String vodPlayUrl) {
        List<String> m3u8Urls = new ArrayList<>();
        if (vodPlayUrl == null || vodPlayUrl.isEmpty()) {
            return m3u8Urls;
        }

        // 使用正则表达式提取m3u8链接
        String[] sources = vodPlayUrl.split("\\$\\$\\$");
        Pattern pattern = Pattern.compile("(?i)\\.m3u8");

        for (String source : sources) {
            String[] items = source.split("#");
            for (String item : items) {
                String[] parts = item.split("\\$");
                if (parts.length >= 2) {
                    String url = parts[1];
                    Matcher matcher = pattern.matcher(url);
                    if (matcher.find()) {
                        m3u8Urls.add(url);
                    }
                }
            }
        }

        return m3u8Urls;
    }
}